package com.thinkcoder.controller;


import com.thinkcoder.constant.ErrorStatus;
import com.thinkcoder.model.query.ExceptionQuery;
import com.thinkcoder.protocol.Result;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/exception")
public class ExceptionController {

    //if校验
/*    @PostMapping("/query")
    public Result  getResult(@RequestBody ExceptionQuery query){
        //校验参数
        if (StringUtils.isEmpty(query.getUserName())){
            return Result.buildFailure(ErrorStatus.ILLEGAL_ARGUMENT.getCode(),ErrorStatus.ILLEGAL_ARGUMENT.getMessage());
        }
        return Result.buildSuccess(query);
    }*/


    //BindingResult拿到异常信息
/*    @PostMapping("/query")
    public Result  getResult(@Valid @RequestBody ExceptionQuery query, BindingResult result){
        if(result.hasErrors()){
            Map<String,String> map = new HashMap<>();
            result.getFieldErrors().forEach(item->{
                //获取发生错误时的message
                String message = item.getDefaultMessage();
                //获取发生错误的字段
                String field = item.getField();
                map.put(field,message);
                System.out.println(field+":"+message);
            });
            return Result.buildFailure(400,"参数错误",map);
        }
        return Result.buildSuccess(query);
    }*/


    //加上全局异常处理的代码
    @PostMapping("/query")
    public Result  getResult(@Valid @RequestBody ExceptionQuery query){
        return Result.buildSuccess(query);
    }



//    @GetMapping("/getname")
//    public Result getResult(@Size(max =3,min = 1) @RequestParam("userName") String userName){
//        return Result.buildSuccess(userName);
//    }
}
